package cn.jdy.common.ctrl;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;

import cn.jdy.authority.entity.User;
import cn.jdy.common.bo.RespBody;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.EncodeUtil;
import cn.jdy.framework.util.WriteExcel;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.service.MemberService;

/**
 * web层基类
 *
 * @author: zhaiGuangtao
 * @data: 2013-7-1
 */
public abstract class BaseCtrl {
	@Autowired
	protected HttpServletRequest request;
	@Autowired
	public  HttpSession session;
	@Autowired
	protected ConfService confService;
	@Autowired
	protected MemberService memberService;
	// do some thiing...

	/**
	 * 模版路径名称
	 */
	protected static final String t = "";// /1
	
	//获取后台用户信息
	protected User getUser() {
		return (User) session.getAttribute("user");
	}

	//获取前台用户信息
	protected Member getMember() {
		return getMember(false);
	}

	//获取前台用户信息
	protected Member getMember(boolean newest) {
		Member member = (Member)session.getAttribute("user");
		return member == null ? null : (newest ? memberService.find(member.getId()) : member);
	}

	/**
	 * @param currentPage 当前页
	 * @param pageSize    每页显示条数
	 * @param InfoCount   所要查询数据的总条数
	 * @return
	 */
	protected Map<String, Integer> getPageInfo(Integer currentPage, Integer pageSize, String InfoCount) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		//每页显示数据条数
		if(null == pageSize || pageSize <= 0) pageSize = 5;
		//根据查询数据的总条数计算总页数
		Integer totalPage = 0;
		if(Integer.parseInt(InfoCount) % pageSize == 0) {
			totalPage = Integer.parseInt(InfoCount) / pageSize;
		} else {
			totalPage = Integer.parseInt(InfoCount) / pageSize + 1;
		}
		//当前页
		if(null == currentPage || currentPage <= 0) {
			currentPage = 1;
		} else if(currentPage > totalPage) {
			currentPage = totalPage;
		}
		map.put("pageSize", pageSize);
		map.put("currentPage", currentPage);
		map.put("totalPage", totalPage);
		return map;
	}

	/**
	 * 获取请求参数 返回HashMap 格式
	 *
	 * @return
	 */
	protected HashMap<String, Object> getReqParamMap() {
		// 使用map接收页面表单参数信息
		HashMap<String, Object> params = new HashMap(request.getParameterMap());

		// 由于接收的map值 Object 内容是String[]格式，在此需要格式转换
		Set<String> keys = params.keySet();
		for(String key : keys) {
			String value = "";
			Object valueObj = params.get(key);
			if(null == valueObj) {
				value = "";
			} else if(valueObj instanceof String[]) {
				String[] values = (String[]) valueObj;
				for(int i = 0; i < values.length; i++) {
					value = values[i] + ",";
				}
				value = value.substring(0, value.length() - 1);
			} else {
				value = valueObj.toString();
			}
			params.put(key, value);
		}
		return params;
	}

	/**
	 * 查询业务分类（智库、新闻、帮助中心等）
	 *
	 * @param type: 配置类型
	 * @return
	 */
	protected List<ConfValue> bizClass(int type) {
		List<ConfValue> plist = null;
		try {
			plist = confService.queryByType(type, 0L,null);
			for(ConfValue bo : plist) {
				bo.setChildren(confService.findConfValueByPid(bo.getId()));
			}
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询文章异常", e);
		}
		return plist;
	}

	/**
	 * 下载到Excel
	 *
	 * @return
	 */
	protected boolean downExcel(List list, String[] titles, Object fieldNames, String name, HttpServletResponse response) {
		if(titles==null || fieldNames==null || name==null) return false;
		WriteExcel we = new WriteExcel();
		HSSFWorkbook wb = we.WriteExcelData(name, titles, fieldNames, list);
		OutputStream writer = null;
		try {
			response.setContentType("application/x-unknown;charset=GB2312");
			response.setHeader("Content-Disposition", "attachment;filename=" + EncodeUtil.ecode(name + ".xls", "UTF-8"));
			writer = response.getOutputStream();
			wb.write(writer);
			return true;
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "下载到Excel异常", e);
			return false;
		} finally {
			if(writer != null) {
				try {
					writer.close();
				} catch(Exception e) {
					BaseLog.e(this.getClass(), "downExcel", e);
				}
			}
		}
	}

	/**
	 * 统一异常处理
	 * @param e
	 * @return
	 */
	@org.springframework.web.bind.annotation.ResponseBody
	@ExceptionHandler(Exception.class)
	public RespBody exceptionHandler(Exception e) {
		BaseLog.e(this.getClass(), "统一异常处理", e);
		return RespBody.error(500, e.getMessage());
	}
}
